<template>
  <div>
    <div>
      <el-form style="text-align: left" :model="searchMsg" status-icon :inline="true" ref="searchFrom"
               label-width="100px" class="demo-form-inline">
        <el-form-item label="用户账号" prop="loginname">
          <el-input v-model.number="searchMsg.loginname"></el-input>
        </el-form-item>
        <el-form-item label="身份证号" prop="identity">
          <el-input v-model="searchMsg.identity" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="realname">
          <el-input v-model="searchMsg.realname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="家庭住址" prop="address">
          <el-input v-model="searchMsg.address" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话号码" prop="phone">
          <el-input v-model="searchMsg.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="职位" prop="position">
          <el-input v-model="searchMsg.position" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio v-model="searchMsg.sex" label="1">男</el-radio>
          <el-radio v-model="searchMsg.sex" label="2">女</el-radio>
        </el-form-item>
        <br>
        <el-form-item style="margin-left:  500px">
          <el-button type="primary" @click="search()">搜索</el-button>
          <el-button @click="restSearch()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div style="text-align: left">
      <el-button type="succes" @click="popAddMenu()">添加一个</el-button>
      <el-button type="danger" @click="removeSelect()">删除选中</el-button>
    </div>
    <el-table
        ref="multipleTable"
        :data="userMsgs"
        tooltip-effect="dark"
        style="width: 100%"
        border
        :header-cell-style="{ textAlign: 'center' }"
        :cell-style="{ textAlign: 'center' }"
        @selection-change="handleSelectionChange">
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>
      <el-table-column
          label="头像"
          width="120">
        <template slot-scope="scope">
          <div class="demo-basic--circle">
            <div class="block" style="padding-top: 20px;padding-bottom: 20px">
              <el-avatar :size="50" :src="scope.row.headurl"></el-avatar>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column
          prop="realname"
          label="姓名"
      >
      </el-table-column>
      <el-table-column
          prop="address"
          label="地址"
      >
      </el-table-column>
      <el-table-column
          prop="phone"
          label="联系电话"
      >
      </el-table-column>
      <el-table-column
          label="性别"
      >
        <template slot-scope="scope">
          {{ scope.row.sex === 1 ? '男' : '女' }}
        </template>
      </el-table-column>
      <el-table-column
          fixed="right"
          label="操作"
          width="350px"
      >
        <template slot-scope="scope">
          <el-button @click="popModifyMenu(scope.row.userid)" type="primary" size="small">编辑</el-button>
          <el-button @click="restPwd(scope.row.userid)" type="warning" size="small">重置密码</el-button>
          <el-button @click="popModifyRole(scope.row.userid)" type="primary" size="small">分配角色</el-button>
          <el-button @click="removeOne(scope.row.userid)" type="danger" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageIndex"
        :page-sizes="[3,5,10,20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
    </el-pagination>
    <el-dialog
        title="添加"
        :visible.sync="addFlag"
        width="30%"
        :before-close="handleClose">
      <el-form :model="userMsg" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户账号" prop="loginname">
          <el-input v-model.number="userMsg.loginname"></el-input>
        </el-form-item>
        <el-form-item label="登陆密码" prop="pwd">
          <el-input v-model="userMsg.pwd" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="身份证号" prop="identity">
          <el-input v-model="userMsg.identity" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="realname">
          <el-input v-model="userMsg.realname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="家庭住址" prop="address">
          <el-input v-model="userMsg.address" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话号码" prop="phone">
          <el-input v-model="userMsg.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="职位" prop="position">
          <el-input v-model="userMsg.position" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio v-model="userMsg.sex" label="1">男</el-radio>
          <el-radio v-model="userMsg.sex" label="2">女</el-radio>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addUser('userMsg')">提交</el-button>
          <el-button @click="resetForm('userMsg')">重置</el-button>
          <el-button @click="addFlag = false">取 消</el-button>
        </el-form-item>
      </el-form>
      <!--      <el-button type="primary" @click="addFlag = false">确 定</el-button>-->
    </el-dialog>
    <!--    修改-->
    <el-dialog
        title="修改"
        :visible.sync="modifyFlag"
        width="30%"
        :before-close="handleClose">
      <el-form :model="userMsg" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户账号" prop="loginname">
          <el-input v-model.number="userMsg.loginname"></el-input>
        </el-form-item>
        <el-form-item label="登陆密码" prop="pwd">
          <el-input v-model="userMsg.pwd" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="身份证号" prop="identity">
          <el-input v-model="userMsg.identity" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="realname">
          <el-input v-model="userMsg.realname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="家庭住址" prop="address">
          <el-input v-model="userMsg.address" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话号码" prop="phone">
          <el-input v-model="userMsg.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="职位" prop="position">
          <el-input v-model="userMsg.position" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio v-model="userMsg.sex" label="1">男</el-radio>
          <el-radio v-model="userMsg.sex" label="2">女</el-radio>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="modifyUser('userMsg')">提交</el-button>
          <el-button @click="resetForm('userMsg')">重置</el-button>
          <el-button @click="modifyFlag = false">取 消</el-button>
        </el-form-item>
      </el-form>
      <!--      <el-button type="primary" @click="addFlag = false">确 定</el-button>-->
    </el-dialog>
    <!--    分配角色-->
    <el-dialog
        title="修改"
        :visible.sync="roleFlag"
        width="40%"
        :before-close="roleHandleClose">
      <el-table
          ref="multipleTable"
          :data="roleMsgs"
          border
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="roleSelectionChange">
        <el-table-column
            type="selection"
            width="55">
        </el-table-column>
        <el-table-column
            prop="roleid"
            label="角色id"
        >
        </el-table-column>
        <el-table-column
            prop="rolename"
            label="角色名字"
        >
        </el-table-column>
        <el-table-column
            prop="roledesc"
            label="角色描述"
        >
        </el-table-column>
      </el-table>
      <el-button type="primary" @click="modifyUserRole()">提交</el-button>
      <el-button @click="roleHandleClose">取 消</el-button>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "usermenu",
  data() {
    // 真实姓名校验
    var checkname = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('真实姓名不能为空'));
      } else if (value === '') {
        callback(new Error('真实姓名得为空字符串'));
      } else {
        callback();
      }
    };
    // 登录信息校验
    var validateLogin = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入账号'));
      } else {
        callback();
      }
    };

    var validatepwd = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('真实姓名不能为空'));
      } else if (value === '') {
        callback(new Error('请输入密码'));
      } else if (value.length < 4) {
        callback(new Error('密码长度应该大于等于4'));
      } else {
        callback();
      }
    };
    return {
      // 用户数据
      userMsgs: [],
      // 选择框数据
      multipleSelection: [],
      // 角色选取框数据
      roleMultipleSelection: [],
      // 分页数据
      pageIndex: 1,
      pageSize: 5,
      total: 0,
      // 添加提示框标记
      addFlag: false,
      // 修改的标记
      modifyFlag: false,
      // 分配角色的标记
      roleFlag: false,
      // 要被添加的用户信息
      userMsg: {
        loginname: '',
        pwd: '',
        realname: '',
        address: '',
        sex: 0,
      },
      // 临时保存的用户id
      tempUserId: 0,
      // 搜索的条件
      searchMsg: {},
      // 角色的全部信息
      roleMsgs: [],
      // 校验规则
      rules: {
        loginname: [
          {validator: validateLogin, trigger: 'blur'}
        ],
        pwd: [
          {validator: validatepwd, trigger: 'blur'}
        ],
        realname: [
          {validator: checkname, trigger: 'blur'}
        ]
      }
    };
  },
  // 页面初始化方法
  created() {
    this.flushPage()
  },
  methods: {
    // 复选框的方法
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 当角色选取框发生改变的时候
    roleSelectionChange(val) {
      this.roleMultipleSelection = val;
    },
    // 分页的方法，当页面大小改变
    handleSizeChange(val) {
      this.pageSize = val
      this.flushPage()
    },
    // 当页面下标改变
    handleCurrentChange(val) {
      this.pageIndex = val
      this.flushPage()
    },
    // 删除这条记录
    removeOne(userid) {
      let ids = []
      ids.push(userid)
      this.removeBeach(ids)
    },
    // 弹出分配用户角色的框
    popModifyRole(userid) {
      // 暂时保存用户的id
      this.tempUserId = userid
      this.$http.get("http://127.0.0.1:8081/User/GetUserRole/" + userid).then(resp => {
        let tempData = resp.data.data;
        if (tempData) {
          tempData.forEach(row => {
            for (let i = 0; i < this.roleMsgs.length; i++) {
              if (row.roleid === this.roleMsgs[i].roleid) {
                this.$refs.multipleTable.toggleRowSelection(this.roleMsgs[i]);
              }
            }
          });
        } else {
          this.$refs.multipleTable.clearSelection();
        }
      })
      this.roleFlag = true
    },
    // 删除选中
    removeSelect() {
      let ids = []
      this.multipleSelection.forEach(row => {
        ids.push(row.userid)
      })
      this.removeBeach(ids)
    },
    // 批量删除记录
    removeBeach(ids) {
      const h = this.$createElement
      // 发送请求
      this.$http.post("http://127.0.0.1:8081/User/Remove", ids).then(resp => {
        if (resp.data.code === 2000) {
          // 消息通知
          this.$notify({
            title: "消息",
            message: h("i", {style: "color: teal"}, resp.data.msg),
            duration: 4000
          })
          // 刷新页面
          this.flushPage()
        }
      })
    },
    // 弹出对话框
    popAddMenu() {
      this.addFlag = true
    },
    // 弹出修改
    popModifyMenu(id) {
      this.$http.get("http://127.0.0.1:8081/User/GetMsg/" + id).then(resp => {
        this.userMsg = resp.data.data
        this.userMsg.pwd=""
      })
      this.modifyFlag = true
    },
    // 重置该用户的密码
    restPwd(uid) {
      this.$http.delete("http://127.0.0.1:8081/User/RestPwd/" + uid).then(resp => {
        if (resp.data.code === 2000) {
          this.$notify({
            title: '成功',
            message: '用户的密码重置成功！默认为123456',
            type: 'success'
          });
        } else {
          this.$notify.error({
            title: '错误',
            message: '密码重置失败'
          });
        }
      })
    },
    // 确定提交添加操作
    addUser() {
      const h = this.$createElement
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          this.$http.post("http://127.0.0.1:8081/User/Add", this.userMsg).then(resp => {
            if (resp.data.code === 2000) {
              // 消息通知
              this.$notify({
                title: "消息",
                message: h("i", {style: "color: teal"}, "用户：" + resp.data.data.realname + " 插入成功！"),
                duration: 4000
              })
            } else {
              this.$notify({
                title: "消息",
                message: h("i", {style: "color: red"}, "插入失败"),
                duration: 4000
              })
            }
            this.handleClose()
            this.flushPage()
          })
        } else {
          this.$notify({
            title: "警告",
            message: "请先正确填写表单信息",
            duration: 4000
          })
          return false;
        }
      });
    },
    // 修改用户信息
    modifyUser() {
      this.$http.post("http://127.0.0.1:8081/User/Modify", this.userMsg).then(resp => {
        if (resp.data.code === 2000) {
          this.$notify({
            title: "消息",
            message: "更新成功",
            duration: 4000
          })
        } else {
          this.$notify.error({
            title: '错误',
            message: '更新失败'
          });
        }
      })
      this.handleClose()
      this.flushPage()
    },
    // 修改用户的权限
    modifyUserRole() {
      let rids = [];
      this.roleMultipleSelection.forEach(e => {
        rids.push(e.roleid)
      })
      this.$http.post("http://127.0.0.1:8081/User/ModifyUserRole/" + this.tempUserId, rids).then(resp => {
        console.log(resp.data.code)
        if (resp.data.code === 2000) {
          this.$notify({
            title: "消息",
            message: "更新成功",
            duration: 4000,
            type: "success"
          })
        }
      })
      this.roleHandleClose()
    },
    // 对话框关闭之后
    handleClose() {
      this.$nextTick(() => {
        this.$refs['ruleForm'].resetFields();
      })
      this.addFlag = false
      this.modifyFlag = false
    },
    roleHandleClose() {
      this.$refs.multipleTable.clearSelection();
      this.roleFlag = false
    },
    resetForm() {

      this.$nextTick(() => {
        this.$refs['ruleForm'].resetFields();
      })
    },
    // 重置搜索菜单
    restSearch() {
      this.$nextTick(() => {
        this.$refs['searchFrom'].resetFields();
      })
    },
    // 执行搜索方法
    search() {
      this.$http.post("http://127.0.0.1:8081/User/GetUsers", this.searchMsg).then(resp => {
        this.userMsgs = resp.data.data
      })
    },
    // 刷新页面的方法
    flushPage() {
      // 获取全部的用户信息
      this.$http.get("http://127.0.0.1:8081/User/List/" + this.pageIndex + "/" + this.pageSize).then(resp => {
        console.log(resp.data.data)
        // 放入用户信息
        this.userMsgs = resp.data.data.records;
        // 放入分页数据
        this.total = resp.data.data.total
      })
      // 获取全部的角色信息
      this.$http.post("http://127.0.0.1:8081/Role/GetRoles", {available: 1}).then(resp => {
        this.roleMsgs = resp.data.data
        console.log(this.roleMsgs)
      })
    }
  }
}

</script>

<style scoped>

</style>
